<template>
	<div>
		<div class="department">
			<!-- 新增科室按钮 -->
			<div class="addRoom_box">
				<el-button type="primary" class="mt10 mr30" style="border-radius: 10px" @click="handleAdd"> 新增科室 </el-button>
			</div>

			<!-- 科室列表 -->
			<div class="department_box">
				<div class="room_title">科室管理</div>

				<!-- 搜索部分 -->
				<div class="search_box">
					<el-input
						placeholder="一级科室名称"
						v-model="searchValue"
						class="search_input ml20"
						style="width: 200px"
						clearable
						@clear="handleSearch"
						@input="handleSearch"
					/>
				</div>

				<el-table
					:data="currentPageData"
					style="width: 100%; margin-bottom: 20px"
					row-key="id"
					default-expand-all
					v-loading="loading"
					element-loading-text="数据加载中..."
				>
					<el-table-column type="selection" width="55" align="center" />
					<el-table-column prop="name" label="科室名称" align="center" />
					<el-table-column prop="heat" label="科室热度" align="center">
						<template #default="scope" align="center">
							<span>{{ scope.row.heat }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="local" label="地点" align="center">
						<template #default="scope">
							<span>{{ scope.row.local }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="doctorCount" label="医生数量" align="center">
						<template #default="scope">
							<span>{{ scope.row.doctorCount }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="create_time" label="创建时间" align="center">
						<template #default="scope">
							<span>{{ scope.row.create_time }}</span>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center">
						<template #default="scope">
							<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
							<el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

					<!-- 分页 -->
				<el-pagination
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-sizes="[10, 20, 50]"
					:page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
					background
					class="pagination-center"
				>
				</el-pagination>
			</div>

			<!-- 新增/编辑科室弹窗 -->
			<el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px" @close="handleDialogClose">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="科室名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入科室名称"></el-input>
        </el-form-item>
        <el-form-item label="上级科室" prop="pid">
    <el-select v-model="form.pid" placeholder="请选择上级科室（可不选）" clearable style="width: 100%;">
        <el-option
            v-for="item in parentDepartments"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
        <el-option :label="'无'" :value="0"></el-option>
    </el-select>
    <div class="tips">提示：一级科室无需选择</div>
</el-form-item>
        <el-form-item label="科室位置" prop="local">
            <el-input v-model="form.local" placeholder="请输入科室位置"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
            <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="科室详情" prop="details" class="department-details-form-item">
            <vue-ueditor-wrap v-model="form.details" :config="editorConfig" editor-id="editor-demo-02"></vue-ueditor-wrap>
        </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
            <el-button @click="handleDialogClose">取 消</el-button>
            <el-button type="primary" @click="submitForm">保 存</el-button>
        </span>
    </template>
</el-dialog>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { departmentList, addDepartment, deleteDepartment } from '/@/api/department/index';

// 富文本
const editorConfig = reactive({
    // 编辑器不自动被内容撑高
    autoHeightEnabled: false,
    // 初始容器高度
    initialFrameHeight: 200,
    // 初始容器宽度
    initialFrameWidth: '100vw',
    UEDITOR_HOME_URL: '/UEditor/', // 访问 UEditor 静态资源的根路径，可参考常见问题1
    serverUrl: '/pc/common/ueditor', // 服务端接⼝
    uploadUrl: '/UEditor',
});

// 定义科室数据接口
interface Department {
	id: number;
	name: string;
	pid: number;
	local: string;
	heat: number;
	doctorCount: number;
	create_time: string;
	status: number;
	details: string;
	children?: Department[];
}

// 将列表数据转换为树形结构的函数
const listToTree = (list: Department[]): Department[] => {
	const map: Record<number, Department> = {};
	const result: Department[] = [];

	// 创建映射关系
	list.forEach((item) => {
		map[item.id] = { ...item, children: [] };
	});

	// 构建树形结构
	list.forEach((item) => {
		const node = map[item.id];
		if (item.pid === 0) {
			result.push(node);
		} else {
			const parentNode = map[item.pid];
			if (parentNode) {
				parentNode.children = parentNode.children || [];
				parentNode.children.push(node);
			}
		}
	});

	return result;
};

// 搜索值
const searchValue = ref('');

// 表格数据
const tableData = ref<Department[]>([]);

// 全量数据（用于前端分页）
const allTableData = ref<Department[]>([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const loading = ref(false);

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增科室');
const isEdit = ref(false);

// 表单引用
const formRef = ref<FormInstance>();

// 富文本编辑器引用
const quillEditorRef = ref();

// 表单数据
const form = reactive({
	id: 0,
	name: '',
	pid: 0,
	local: '',
	heat: 0,
	doctorCount: 0,
	create_time: '',
	status: 1,
	details: '',
});

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入科室名称', trigger: 'blur' }
    ],
    local: [
        { required: true, message: '请输入科室位置', trigger: 'blur' }
    ],
    details: [
        { required: true, message: '请输入科室详情', trigger: 'blur' }
    ]
    // 上级科室不是必填项，所以不添加验证规则
}

// 上级科室列表
const parentDepartments = computed(() => {
    // 只选择一级科室作为上级科室选项（pid为0的科室）
    return allTableData.value.filter(item => item.pid === 0 && item.id !== form.id)
})

// 当前页数据（支持前端分页和搜索）
const currentPageData = computed(() => {
	// 先进行搜索过滤
	let filteredData = allTableData.value;
	if (searchValue.value) {
		filteredData = allTableData.value.filter((item) => item.name.includes(searchValue.value));
	}

	// 更新总数量
	total.value = filteredData.length;

	// 再进行分页
	const start = (currentPage.value - 1) * pageSize.value;
	const end = start + pageSize.value;

	return filteredData.slice(start, end);
});

// 获取科室列表
const getDepartmentList = async () => {
	loading.value = true;
	try {
		const res = await departmentList().signIn({});
		if (res.code === 1) {
			// 转换为树形结构
			const treeData = listToTree(res.data);
			allTableData.value = treeData;
			tableData.value = treeData;

			// 更新总数量
			total.value = treeData.length;
		} else {
			ElMessage.error(res.msg || '获取科室列表失败');
		}
	} catch (error) {
		ElMessage.error('获取科室列表失败');
		console.error(error);
	} finally {
		loading.value = false;
	}
};



// 处理删除科室
const handleDelete = (row: Department) => {
	ElMessageBox.confirm('确定要删除该科室吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				const res = await deleteDepartment({ id: row.id });
				if (res.code === 1) {
					ElMessage.success('删除成功');
					getDepartmentList(); // 重新获取数据
				} else {
					ElMessage.error(res.msg || '删除失败');
				}
			} catch (error) {
				ElMessage.error('删除失败');
				console.error(error);
			}
		})
		.catch(() => {
			ElMessage.info('已取消删除');
		});
};

// 处理搜索
const handleSearch = () => {
	// 搜索时重置到第一页
	currentPage.value = 1;
};

// 清空富文本编辑器
const clearQuillEditor = () => {
    nextTick(() => {
        if (quillEditorRef.value) {
            try {
                // 使用 Quill Editor 的 API 清空内容
                const quill = quillEditorRef.value.getQuill()
                quill.setText('')
                form.details = ''
            } catch (error) {
                // 如果 getQuill 方法不可用，使用备用方法
                form.details = ''
            }
        }
    })
}

// 重置表单
const resetForm = () => {
    Object.assign(form, {
        id: 0,
        name: '',
        pid: 0,  // 默认为0，表示一级科室
        local: '',
        heat: 0,
        doctorCount: 0,
        create_time: '',
        status: 1,
        details: ''
    })
    
    // 清除表单验证
    nextTick(() => {
        formRef.value?.clearValidate()
    })
}

// 关闭弹窗
const handleDialogClose = () => {
    dialogVisible.value = false
    resetForm()
    clearQuillEditor()
}

// 处理新增科室
const handleAdd = () => {
    dialogTitle.value = '新增科室'
    isEdit.value = false
    resetForm()
    
    // 先清空富文本编辑器
    clearQuillEditor()
    
    // 然后打开弹窗
    dialogVisible.value = true
}

// 处理编辑科室
const handleEdit = (row: Department) => {
    dialogTitle.value = '编辑科室'
    isEdit.value = true
    Object.assign(form, row)
    dialogVisible.value = true
    
    // 确保 pid 为数字类型
    if (form.pid === null || form.pid === undefined) {
        form.pid = 0
    }
    
    // 编辑时不需要清空编辑器，保留已有内容
    nextTick(() => {
        if (quillEditorRef.value && form.details) {
            // 内容已经在 form.details 中，无需额外处理
        }
    })
}
// 提交表单
const submitForm = () => {
    formRef.value?.validate(async (valid) => {
        if (valid) {
            try {
                // 处理表单数据
                const formData = { ...form };
                
                // 确保 pid 为数字类型，如果为空则设置为 0
                if (formData.pid === null || formData.pid === undefined || formData.pid === '') {
                    formData.pid = 0;
                }
                
                // 如果是编辑状态且正在将科室设为自己的子科室，则阻止操作
                if (isEdit.value && formData.pid === formData.id) {
                    ElMessage.error('不能将科室设置为自己的子科室')
                    return
                }
                
                const res = await addDepartment(formData)
                if (res.code === 1) {
                    ElMessage.success(`${isEdit.value ? '编辑' : '新增'}科室成功`)
                    handleDialogClose()
                    getDepartmentList() // 重新获取数据
                } else {
                    ElMessage.error(res.msg || `${isEdit.value ? '编辑' : '新增'}科室失败`)
                }
            } catch (error) {
                ElMessage.error(`${isEdit.value ? '编辑' : '新增'}科室失败`)
                console.error(error)
            }
        }
    })
}

// 分页相关方法
const handleSizeChange = (val: number) => {
	pageSize.value = val;
	currentPage.value = 1;
};

const handleCurrentChange = (val: number) => {
	currentPage.value = val;
};

// 页面加载时获取数据
onMounted(() => {
	getDepartmentList();
});
</script>

<style scoped>
.addRoom_box{
    display: flex;
    width: 100%;
	height: 60px;
	background-color: #f3f8ff;
	align-items: center;
	justify-content: end;
    padding: 0 30px;
}

/* 科室部分 */
.department_box {
	width: 98%;
	min-height: 80vh;
	margin-left: 1%;
	border-radius: 5px;
	background: #fff;
	> .room_title {
		width: 100%;
		height: 50px;
		font-weight: 700;
		font-size: 23px;
		line-height: 50px;
		background-color: #fff;
		display: flex;
		justify-content: flex-start;
		padding-left: 20px;
	}
}

.search_box {
	display: flex;
	align-items: center;
	padding: 10px 0;
	flex-wrap: wrap;
}

.pagination-center {
	display: flex;
	justify-content: center;
	margin-top: 20px;
}
.dialog-footer {
    text-align: right;
}

.tips {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
}

/* 富文本编辑器样式优化 */
.department-details-form-item :deep(.el-form-item__content) {
    display: block;
}

.department-details-form-item :deep(.ql-container) {
    min-height: 200px;
}
</style>
